import React, { Component } from 'react';
import { 
  Tab, Table, Pagination, Loading, 
  Animate, Dialog, Button,
  Form, Select, Message, Input,
 } from '@alifd/next';
import {
  refreshAble,
  BatchWrapper,
} from '@src/components/index';
import {
    requestTaskList,
} from './reducer/ProcessTaskAction';
import FoundationSymbol from '@icedesign/foundation-symbol';
import { withRouter } from 'react-router';
import { 
  ApprovalDialog, 
  SearchFilter 
} from './components';

import './ProcessTask.scss'

const tabs = [
    { tab: '流程任务管理', key: 0,},
];

@withRouter
@refreshAble('ProcessTask')
export default class ProcessTask extends Component {
  static displayName = 'ProcessTask';

  constructor(props) {
    super(props);
    this.state = {
      current: 1,
      dataSource: [],
      loading: false,
      height: `${document.documentElement.clientHeight - 260}px`,
      basicDetail: {},
      logList: {},
      taskId: '',
      isShowBatch: false,
      isShowApproval: false,
      selectUser: '',
    };
  }

  componentDidMount () {
    this.onRefresh({current: 1, user: 1, group: 1});

    window.addEventListener('resize', this.handleHeight);
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleHeight);

    this.props.fetchDataCancle();
  }

  onRefresh = (data) => {
    this.props.fetchData(requestTaskList(data));
  }

  handleHeight = () => {
    const screenHeight = document.documentElement.clientHeight;
    let height = `${screenHeight - 260}px`;
    if (screenHeight < 472) {
      height = 'auto'
    }

    this.setState({
      height
    })
  }

  handleSort = (dataIndex, order) => {
    const dataSource = this.state.dataSource.sort((a, b) => {
      const result = a[dataIndex] - b[dataIndex];
      if (order === 'asc') {
        return result > 0 ? 1 : -1;
      }
      return result > 0 ? -1 : 1;
    });

    this.setState({
      dataSource,
    });
  };

  setCellProps = (rowIndex, colIndex, dataIndex, record) => {
    //console.log('my record==',record)
    const { id } = record;
    let that = this;
    if (colIndex === 1) {
        let propsConf = {
            style: {color: '#3ea8f5', cursor: 'pointer'},
            onClick: (event) => {
                event.stopPropagation();
                that.setState({
                  taskId: id
                })
            },
        }
        return propsConf;
    }
  }

  hideShow = (event,obj) => {
    if (this.state.isShow) {
      this.setState({
          isShow: false
     })
    }
}

  setRowProps = (record, index) => {
    return {
        style: {height: '60px',fontSize: '14px'}
    }
  }

  handlePagination = (current) => {
    this.setState({
      current: current
    })
    this.props.fetchData(requestTaskList({
      current: current, 
      user: this.state.selectUser ? this.state.selectUser : 1, 
      group: 1
    }));
  };

  renderTableColumn = (headerDatas) => {
    if (headerDatas && headerDatas.length > 0) {
      return headerDatas.map((item, index) => {
        return (
          <Table.Column
            title={item.headerName}
            dataIndex={item.headerKey}
            key={index}
            cell={item.cell || ((value) => value)}
            width={220 || 'auto'}
            height={50}
          />
        )
      })
    }
  }

  rowOnSelect = (selected, record, records) => {
    console.log(record)
    const { id } = record;
    this.setState({
      isShowBatch: true,
      taskId: id,
    })
  }

  hideBatchWrapper = (event) => {
    event.stopPropagation();
    this.setState({
      isShowBatch: false
    })
  }

  onShowApproval = () => {
    this.setState({
      isShowApproval: true
    })
  }

  onHideApproval = (type) => {
    if (type == "close") {
      this.setState({
        isShowApproval: false,
      })
    } else {
      this.setState({
        isShowApproval: false,
        isShowBatch: false
      })
    }
  }

  onViewProcess = (taskId) => {
    //window.open('http://10.10.37.60:8841/static/processImage.html?taskId='+taskId)
    let _url = "http://10.10.37.60:8841/static/processImage.html?taskId=" + taskId;
    Dialog.show({
      title:"审批",
      content: <iframe src={_url} width="1000" height="500"></iframe>
    })
  }

  renderBtnItem = () => {
    const { taskId } = this.state;
    return (
      <div className="batch-btns">
          <div className="btn-item" onClick={() => {this.onShowApproval(taskId)}}>
              <FoundationSymbol size="small" type={'repair'} />
              <span>审批</span>
          </div>
          <div className="btn-item" onClick={() => {this.onViewProcess(taskId)}}>
              <FoundationSymbol size="small" type={'repair'} />
              <span>查看流程图</span>
          </div>
      </div>
    )
  }

  selectUser = (values) => {
    this.setState({
      selectUser: values.user
    })
  }

  render() {

    const { 
      loading, 
      isShowBatch,
      isShowApproval,
      taskId,
     } = this.state;

    const { 
      data, 
      isRefreshing,
    } = this.props;

    let tableDataValues, tableHeaders, totalCount;
    if (data && data.data) {
      tableDataValues = data.data.tableDataValues;
      tableHeaders = data.data.tableHeaders;
      totalCount = data.data.totalCount;
    }
    //console.log('this.props===',this.props);

    return (
        <div className="layout-content-box">
            {
              isShowApproval ? (
                <ApprovalDialog 
                  taskId={taskId}
                  isShowApproval={isShowApproval}
                  onHideApproval={this.onHideApproval}
                  onRefresh={this.onRefresh}
                />
              ) : null
            }

            <Animate animation={{
              enter: 'expandInDown',
              leave: 'expandOutUp'
            }}>
              {
                isShowBatch ? (<BatchWrapper 
                  hideBatchWrapper={this.hideBatchWrapper} 
                  renderBtnItem={this.renderBtnItem()}
                  />) : null
              }
            </Animate>
            <Tab>
                <Tab.Item title={tabs[0].tab} key={tabs[0].key}>

                  <SearchFilter
                    onRefresh={this.onRefresh}
                    selectUser={this.selectUser}
                  />

                  <Table
                      dataSource={tableDataValues ? tableDataValues : []}
                      onSort={this.handleSort}
                      hasBorder={false}
                      className="custom-table"
                      primaryKey={"id"}   //启用可选后指定的Key
                      rowSelection={{
                        mode:'single',
                        onSelect: this.rowOnSelect
                      }}  //启用可选
                      //getCellProps={this.setCellProps}
                      getRowProps={this.setRowProps}
                      fixedHeader={true}
                      maxBodyHeight={this.state.height}
                      loading={isRefreshing}
                      style={{borderBottom: '1px solid #DCDEE3'}}
                  >
                      {this.renderTableColumn(tableHeaders)}
                  </Table>
                  <Pagination
                      pageSize={10}
                      className="pagination"
                      current={this.state.current}
                      onChange={this.handlePagination}
                      total={parseInt(totalCount)} 
                      totalRender={total => `Total: ${parseInt(totalCount)}`}
                      />
                </Tab.Item>
            </Tab>
        </div>
    );
  }
}